package com.digitalchina.lxnsy.activity.old;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.CityWithTypeV2Adapter;
import com.digitalchina.lxnsy.api.BusinessRealTimePrice;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PriceCountyDataVO;
import com.digitalchina.lxnsy.entity.PriceTabV2VO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.view.MyMarkerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/7/28 15:02
 * 修改备注：
 * ================================================
 */
public class RealTimeMarketV2Activity extends BaseActivity {

    @Bind(R.id.recyclerViewType)
    EasyRecyclerView recyclerViewType;
//    private List<TopSortVO> twoList = new ArrayList<>(); // 第2行分类(3级)

    TextView marketTvTodayPrice;
    TextView marketTvTodayPriceUnit;
    TextView marketTvHighsLowsRange;
    TextView marketTvHighsLowsUnit;
    LineChart mChart;
    TextView marketTvChartText;


    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;

    private RecyclerArrayAdapter adapterH;

    private CityWithTypeV2Adapter adapter;
    private PriceTabV2VO priceTabV2VO;
    private ArrayList<Object> arrAll = new ArrayList<>();

    private List<String> xTime = new ArrayList<>();
    // 展示列表图
    private List<PriceTabV2VO> hisList = new ArrayList<>();

    private View headView;//头布局
    private String highestPrice = ""; // 最高价格

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_realtime_market);
        setTitle("价格详情");
    }

    @Override
    public void initMember() {

        Map<String, Object> map = (Map<String, Object>) getIntent().getSerializableExtra("map");

        priceTabV2VO = (PriceTabV2VO) map.get("PriceTabV2VO");

//        String produceCode = "";
//        if (!map.get("i").equals("0")) // 全部分类
        String produceCode = priceTabV2VO.getProduceCode().getCode();
//        twoList = (List<TopSortVO>) map.get("twoList");
//        twoList.remove(0);

//        TopSortVO vo = new TopSortVO();
//        vo.setSelect(true);
//        vo.setCode(priceTabV2VO.getProduceCode().getCode());
//        vo.setName(priceTabV2VO.getProduceCode().getName());
//
//        for (int i = 0; i < twoList.size(); i++) {
//            if (priceTabV2VO.getProduceCode().getCode().equals(twoList.get(i).getCode())) {
//                twoList.remove(i);
//                break;
//            }
//        }

//        twoList.add(0, vo);

        initHeadView();

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CityWithTypeV2Adapter(this);
        recyclerView.setAdapter(adapter);

        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {

                return headView;
            }

            @Override
            public void onBindView(View headerView) {


            }
        });


//        recyclerViewType.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
//        recyclerViewType.setAdapter(adapterH = new RecyclerArrayAdapter(this) {
//            @Override
//            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
//                return new TopTypeHolder(parent);
//            }
//        });
//
//        adapterH.addAll(twoList);

        BusinessRealTimePrice.getProducePriceStatisticsDetailsV2(this, priceTabV2VO.getFarmProductCode(), produceCode, priceTabV2VO.getCountyCode(), mHandler);
    }

    private void initHeadView() {

        headView = LayoutInflater.from(this).inflate(R.layout.headview_realtime_market, null);
        marketTvTodayPrice = (TextView) headView.findViewById(R.id.market_tv_today_price);
        marketTvTodayPriceUnit = (TextView) headView.findViewById(R.id.market_tv_today_price_unit);
        marketTvHighsLowsRange = (TextView) headView.findViewById(R.id.market_tv_highsLowsRange);
        marketTvHighsLowsUnit = (TextView) headView.findViewById(R.id.market_tv_highsLows_unit);
        marketTvChartText = (TextView) headView.findViewById(R.id.market_tv_chart_text);
        mChart = (LineChart) headView.findViewById(R.id.line_chart);

        marketTvTodayPrice.setText(priceTabV2VO.getPerDayPrice());
        marketTvTodayPriceUnit.setText(priceTabV2VO.getPriceUnit());
        marketTvHighsLowsRange.setText(priceTabV2VO.getHighsLowsRange() + "");
        marketTvChartText.setText(priceTabV2VO.getProvinceName() + priceTabV2VO.getRegionInfo() + "均价走势图");
    }

    @Override
    public void addListener() {
//        adapterH.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(int position) {
//                if (twoList.get(position).isSelect())
//                    return;
//                for (int i = 0; i < twoList.size(); i++) {
//                    twoList.get(i).setSelect(i == position);
//                }
//                adapterH.notifyDataSetChanged();
//                BusinessRealTimePrice.getProducePriceStatisticsDetailsV2(RealTimeMarketV2Activity.this, twoList.get(position).getCode(), priceTabV2VO.getCountyCode(), mHandler);
//            }
//        });
    }

    @Override
    public void setHandler() {

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_GET_PRICE_V2_DETAILS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_PRICE_V2_DETAILS_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

        List<PriceCountyDataVO> list = FastJsonUtil.getListBean(object.toString(), "detailList", PriceCountyDataVO.class);
        hisList = FastJsonUtil.getListBean(object.toString(), "hisList", PriceTabV2VO.class);
        highestPrice = FastJsonUtil.getString(object.toString(), "highestPrice");

        arrAll.clear();
        adapter.clear();

        for (int i = 0; i < list.size(); i++) {
            arrAll.add(list.get(i));
            for (int j = 0; j < list.get(i).getCountyDataList().size(); j++) {
                arrAll.add(list.get(i).getCountyDataList().get(j));
            }
        }

        adapter.addAll(arrAll);

        new Thread() {
            public void run() {
                mHandler.post(runnableUi);
            }
        }.start();

    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            xTime.clear();
            initLineChart();
            //更新界面
            setData(hisList);
        }
    };

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 设置线性表格
     */
    private void initLineChart() {

        mChart.setDrawGridBackground(false);
        mChart.setNoDataText("正在加载");

        // no description text
        mChart.getDescription().setEnabled(false);

        // enable touch gestures
        mChart.setTouchEnabled(true);

        // enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(true);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart

        XAxis xAxis = mChart.getXAxis();
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xTime.get((int) value % xTime.size());
            }
        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        leftAxis.setAxisMaximum(Float.parseFloat(highestPrice));
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawZeroLine(false);
//        leftAxis.setValueFormatter(new CustomYValueFormatter(true));

        // limit lines are drawn behind data (and not on top)
        leftAxis.setDrawLimitLinesBehindData(true);

        mChart.getAxisRight().setEnabled(false);

        // add data
//        setData(realTimeListVOList);

        mChart.animateX(2500);

        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();

        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);

        // // dont forget to refresh the drawing
        mChart.invalidate();

    }

    private void setData(List<PriceTabV2VO> listVOs) {


        if (listVOs == null || listVOs.size() == 0) {
            mChart.setData(new LineData());
            mChart.getLineData().notifyDataChanged();
            mChart.notifyDataSetChanged();
            mChart.invalidate();
            return;
        }

//        if (xTime.size() > 0) //清除已有x轴的数据
//            xTime.clear();

//        mChart.clear();


        ArrayList<Entry> priceToday = new ArrayList<>();


        for (int i = 0; i < listVOs.size(); i++) {
            priceToday.add(new Entry(i, Float.parseFloat(listVOs.get(i).getPerDayPrice())));
            xTime.add(listVOs.get(i).getCollectDate().substring(5, 10));
        }

        LineDataSet set1;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(priceToday);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(priceToday, "平均价格");

            // set the line to be drawn like this "- - - - - -"
            set1.enableDashedLine(10f, 5f, 0f);
            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(getResources().getColor(R.color.app_color));
            set1.setCircleColor(getResources().getColor(R.color.app_color));
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            set1.setDrawCircleHole(true);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(true);
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);
            set1.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                    DecimalFormat df = new DecimalFormat("#.00");
                    return df.format(entry.getY());
                }
            });
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);


            if (Utils.getSDKInt() >= 18) {
                // fill drawable only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_9bdada);
                set1.setFillDrawable(drawable);
            } else {
                set1.setFillColor(Color.parseColor("#9BDADA"));
            }

            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            dataSets.add(set1); // add the datasets

            // create a data object with the datasets
            LineData data = new LineData(dataSets);

            // set data
            mChart.setData(data);
            mChart.getLineData().notifyDataChanged();
            mChart.notifyDataSetChanged();
            mChart.invalidate();
        }
    }
}
